package com.roadjava.util;

import com.alibaba.fastjson.JSON;
import com.roadjava.bean.ClassDefinition;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 * @author zhaodaowen
 * @see <a href="http://www.roadjava.com">乐之者java</a>
 */
public class FreemarkerUtil {
    private static Configuration cfg=null;
    static{
        cfg=new Configuration(Configuration.VERSION_2_3_0);
        cfg.setClassForTemplateLoading(FreemarkerUtil.class, "/tpls/");
        // 配置模板修改后立即生效另外还要配置ideaupdate class and resources 才能
        // 实时编译到target
        cfg.setTemplateUpdateDelayMilliseconds(0L);
    }

    public static Template getTemplate(String templateName){
        try {
            return cfg.getTemplate(templateName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

        FreemarkerUtil.parse2Str("index.ftl",null);
    }
    public static String parse2Str(String templateName,Object mapData){
        Template template = getTemplate(templateName);
        if (template == null) {
            throw  new RuntimeException("模板无法获取");
        }
        // main:utf-8  inexcontroller-->gbk 修改catalina.bat增加
        // set "JAVA_OPTS=%JAVA_OPTS% -Dfile.encoding=UTF-8" idea tomcat日志乱码，
        // 在idea64.exe.vmoptions增加-Dfile.encoding=UTF-8
        System.out.println(template.getEncoding());
        try(StringWriter stringWriter = new StringWriter()) {
            template.process(mapData, stringWriter);
            return stringWriter.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
